package com.jinarusha.shareprayers;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class PrayerListActivity extends Activity {
	protected static final String TAG = "PrayerListActivity";
	private boolean registered = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//should run this only once!!!
		obtainUserPhoneNumber();
		
		// test code
		Intent registrationIntent = new Intent(
				"com.google.android.c2dm.intent.REGISTER");
		registrationIntent.putExtra("app",
				PendingIntent.getBroadcast(this, 0, new Intent(), 0));
		registrationIntent.putExtra("sender", Config.C2DM_SENDER);
		startService(registrationIntent);
		// end of test code
		


		/** setup onclick eventlisteners for the my prayer button */
		((ImageButton) findViewById(R.id.myprayers_btn))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {

						try {
							
//							// 메시지를 보낼때 sender(발급받은 ID, 토큰인증값, 메시지)
//
//							sender(C2DMReceiver.registrationID, getAuthToken(),
//									"test");
//							Log.d(TAG, "registrationID : "
//									+ C2DMReceiver.registrationID);
							
							NetworkCommunication.sendMessage("tempuserid", "tempuserid", "test msg to self");

						} catch (Exception e) {

							// TODO Auto-generated catch block

							e.printStackTrace();

						}

						// Toast msg = Toast.makeText(getApplicationContext(),
						// "my prayer btn clicked", 1);
						// msg.show();

					}
				});

		/** setup onclick eventlisteners for the prayer target button */
		((ImageButton) findViewById(R.id.praytarget_btn))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						Toast msg = Toast.makeText(getApplicationContext(),
								"prayer target clicked", 1);
						msg.show();

					}
				});

		/** setup onclick eventlisteners for thereachout_btn */
		((ImageButton) findViewById(R.id.reachout_btn))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						Toast msg = Toast.makeText(getApplicationContext(),
								"reachout btnclicked", 1);
						msg.show();

					}
				});

		/** setup onclick eventlisteners for the options button */
		((ImageButton) findViewById(R.id.option_btn))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						Toast msg = Toast.makeText(getApplicationContext(),
								"options clicked", 1);
						msg.show();

					}
				});

	}

	// needs to be moved to server side. slow on mobile
	public String getAuthToken() throws Exception {
		String authtoken = "";
		StringBuffer postDataBuilder = new StringBuffer();
		postDataBuilder.append("accountType=HOSTED_OR_GOOGLE");
		postDataBuilder.append("&Email="+Config.C2DM_SENDER);
		postDataBuilder.append("&Passwd="+Config.C2DM_SENDER_PW);
		postDataBuilder.append("&service=ac2dm");
		postDataBuilder.append("&source=test.0");
		byte[] postData = postDataBuilder.toString().getBytes("UTF8");
		URL url = new URL("https://www.google.com/accounts/ClientLogin");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length",
				Integer.toString(postData.length));
		OutputStream out = conn.getOutputStream();
		out.write(postData);
		out.close();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		String sidLine = br.readLine();
		String lsidLine = br.readLine();
		String authLine = br.readLine();
		System.out.println("sidLine———–>>>" + sidLine);
		System.out.println("lsidLine———–>>>" + lsidLine);
		System.out.println("authLine———–>>>" + authLine);
		System.out.println("AuthKey———–>>>"
				+ authLine.substring(5, authLine.length()));
		authtoken = authLine.substring(5, authLine.length());
		return authtoken;

	}

	public void sender(String regId, String authToken, String msg)
			throws Exception {
		StringBuffer postDataBuilder = new StringBuffer();
		postDataBuilder.append("registration_id=" + regId);
		postDataBuilder.append("&collapse_key=1");
		postDataBuilder.append("&delay_while_idle=1");
		postDataBuilder.append("&data.msg=" + URLEncoder.encode(msg, "UTF-8"));
		byte[] postData = postDataBuilder.toString().getBytes("UTF8");
		URL url = new URL("https://android.apis.google.com/c2dm/send");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length",
				Integer.toString(postData.length));
		conn.setRequestProperty("Authorization", "GoogleLogin auth="
				+ authToken);
		OutputStream out = conn.getOutputStream();
		out.write(postData);
		out.close();
		Log.d(TAG, "wrote message: " + msg);

		// need the following line to read one line - for no reason.
		BufferedReader br = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		System.out.println("output msg" + br.readLine());

	}

	public boolean isRegistered() {
		return registered;
	}

	public void setRegistered(boolean registered) {
		this.registered = registered;
	}
	
	//should only run once right after installation
	public void obtainUserPhoneNumber(){
		 TelephonyManager mTelephonyMgr;
	        mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
	        Config.setUSER_PHONE_NUMBER(mTelephonyMgr.getLine1Number());
	}

}